"""
FastAPI Application Entry Point
AI智能体电商客服系统
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager

from app.config import settings
from app.utils.logger import setup_logger, logger
from app.db import (
    init_database,
    close_database,
    init_redis,
    close_redis,
    init_vector_db,
    close_vector_db,
    check_database_health,
    check_redis_health,
    check_vector_db_health,
)
from app.db.vector_db import vector_db_manager
from app.core import init_llm


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events"""
    # Startup
    logger.info("=" * 60)
    logger.info(f"🚀 {settings.APP_NAME} v{settings.APP_VERSION} 启动中...")
    logger.info(f"环境: {settings.ENV} | 调试模式: {settings.DEBUG}")
    logger.info("=" * 60)
    
    try:
        # 初始化数据库
        logger.info("📦 初始化PostgreSQL数据库...")
        await init_database()
        logger.info("✅ PostgreSQL数据库初始化完成")
        
        # 初始化Redis
        logger.info("📦 初始化Redis...")
        await init_redis()
        logger.info("✅ Redis初始化完成")
        
        # 初始化向量数据库
        logger.info("📦 初始化向量数据库...")
        init_vector_db()
        logger.info("✅ 向量数据库初始化完成")
        
        # 初始化LLM
        logger.info("🤖 初始化大语言模型...")
        try:
            init_llm()
            logger.info("✅ LLM初始化完成")
        except Exception as e:
            logger.warning(f"⚠️ LLM初始化失败: {e}（可能未配置API Key）")
        
        # 构建知识库（如果需要）
        logger.info("📚 检查知识库...")
        try:
            doc_count = vector_db_manager.collection.count()
            if doc_count == 0:
                logger.info("知识库为空，开始构建...")
                if vector_db_manager.build_knowledge_base():
                    logger.info("✅ 知识库构建完成")
                else:
                    logger.warning("⚠️ 知识库构建失败（可能没有文档）")
            else:
                logger.info(f"✅ 知识库已就绪 ({doc_count} 个文档块)")
        except Exception as e:
            logger.warning(f"⚠️ 知识库检查失败: {e}")
        
        logger.info("=" * 60)
        logger.info("🎉 所有服务启动成功！")
        logger.info(f"📖 API文档: http://{settings.HOST}:{settings.PORT}{settings.API_PREFIX}/docs")
        logger.info("=" * 60)
        
        yield
        
    except Exception as e:
        logger.error(f"❌ 启动失败: {e}")
        raise
    finally:
        # Shutdown
        logger.info("🔄 正在关闭服务...")
        await close_database()
        await close_redis()
        close_vector_db()
        logger.info("👋 服务已关闭")


# Create FastAPI app
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="基于大语言模型的智能客服系统",
    docs_url=f"{settings.API_PREFIX}/docs",
    redoc_url=f"{settings.API_PREFIX}/redoc",
    openapi_url=f"{settings.API_PREFIX}/openapi.json",
    lifespan=lifespan,
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_ALLOW_METHODS,
    allow_headers=settings.CORS_ALLOW_HEADERS,
)


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "message": f"Welcome to {settings.APP_NAME}",
        "version": settings.APP_VERSION,
        "status": "running",
        "docs": f"{settings.API_PREFIX}/docs"
    }


@app.get("/health")
async def health_check():
    """Health check endpoint"""
    # 检查各个服务的健康状态
    db_healthy = await check_database_health()
    redis_healthy = await check_redis_health()
    vector_db_healthy = check_vector_db_health()
    
    overall_healthy = db_healthy and redis_healthy and vector_db_healthy
    
    return JSONResponse(
        status_code=200 if overall_healthy else 503,
        content={
            "status": "healthy" if overall_healthy else "unhealthy",
            "service": settings.APP_NAME,
            "version": settings.APP_VERSION,
            "environment": settings.ENV,
            "services": {
                "database": "ok" if db_healthy else "error",
                "redis": "ok" if redis_healthy else "error",
                "vector_db": "ok" if vector_db_healthy else "error",
            }
        }
    )


@app.get(f"{settings.API_PREFIX}/ping")
async def ping():
    """Ping endpoint"""
    return {"message": "pong"}


# API Routes
from app.api import auth, chat, order, product

app.include_router(
    auth.router,
    prefix=f"{settings.API_PREFIX}/auth",
    tags=["用户认证"]
)
app.include_router(
    chat.router,
    prefix=f"{settings.API_PREFIX}/chat",
    tags=["聊天对话"]
)
app.include_router(
    order.router,
    prefix=f"{settings.API_PREFIX}/orders",
    tags=["订单管理"]
)
app.include_router(
    product.router,
    prefix=f"{settings.API_PREFIX}/products",
    tags=["商品查询"]
)


if __name__ == "__main__":
    import uvicorn
    
    # 设置日志
    setup_logger()
    
    # 运行应用
    uvicorn.run(
        "app.main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.RELOAD and settings.ENV == "development",
        log_level=settings.LOG_LEVEL.lower(),
    )


